/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.portlet.editor.gui.view.internal.panel;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.server.UID;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JPanel;

import com.genia.toolbox.basics.editor.gui.view.internal.panel.ElementViewPanel;
import com.genia.toolbox.portlet.editor.gui.PortletEditorGUI;
import com.genia.toolbox.portlet.editor.gui.view.internal.PortletDocumentInternalFrame;
import com.genia.toolbox.portlet.editor.gui.view.internal.PortletViewFactory;
import com.genia.toolbox.portlet.editor.model.portlet.PortletType;
import com.genia.toolbox.portlet.editor.model.portlet.impl.ContainerPortletModel;
import com.genia.toolbox.portlet.editor.model.portlet.impl.PortletModel;
import com.genia.toolbox.web.portlet.description.ContainerPortletDescription.LayoutDirection;

/**
 * The container view panel.
 */
@SuppressWarnings("serial")
public class ContainerPortletViewPanel
    extends AbstractPortletViewPanel
{

  /**
   * The view factory. Used to create the sub panels.
   */
  private PortletViewFactory portletViewFactory = null;

  /**
   * The sub panels list.
   */
  private List<ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType>> subViewPanels = null;



  /**
   * Constructor.
   * 
   * @param portletEditorGUI
   *          The portletEditorGUI.
   * @param internalFrame
   *          The internal frame.
   */
  public ContainerPortletViewPanel(PortletEditorGUI portletEditorGUI, PortletDocumentInternalFrame internalFrame)
  {
    super(portletEditorGUI, internalFrame);
    this.portletViewFactory = internalFrame.getViewFactory();
    this.subViewPanels = new LinkedList<ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType>>();
  }



  /**
   * Create the portlet type.
   * 
   * @return the portlet type.
   */
  @Override
  public PortletType getElementType()
  {
    return PortletType.Container;
  }



  /**
   * Create the specific panel.
   * 
   * @return the specific panel.
   */
  @Override
  public JPanel createSpecificPanel()
  {
    JPanel panel = new JPanel();
    panel.addMouseListener(new MouseAdapter()
    {
      /**
       * The mouse clicked event.
       * 
       * @param e
       *          the mouse event.
       */
      @Override
      public void mouseClicked(MouseEvent e)
      {
        ContainerPortletViewPanel.this.deactivateParent();
        if (ContainerPortletViewPanel.this.isCommonSelected()) {
          ContainerPortletViewPanel.this.deactivateAll();
          ContainerPortletViewPanel.this.getGui().displayCurrentDocumentSettings();
        }
        else {
          ContainerPortletViewPanel.this.activateCommon(true);
          ContainerPortletViewPanel.this.deactivateSpecific();
          ContainerPortletViewPanel.this.getGui().displayElementSettings(ContainerPortletViewPanel.this.getElement());
        }
      }



      /**
       * The mouse pressed event.
       * 
       * @param e
       *          the mouse event.
       */
      @Override
      public void mousePressed(MouseEvent e)
      {
        ContainerPortletViewPanel.this.maybeShowPopup(e);
      }



      /**
       * The mouse released event.
       * 
       * @param e
       *          the mouse event.
       */
      @Override
      public void mouseReleased(MouseEvent e)
      {
        ContainerPortletViewPanel.this.maybeShowPopup(e);
      }
    });
    return panel;
  }



  /**
   * Select the panel of a sub-portlet.
   * 
   * @param index
   *          the index of the sub-portlet.
   */
  public void selectSubPortlet(Integer index)
  {
    this.deactivateAll();
    if (index != -1) {
      ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> panel = this.subViewPanels.get(index);
      panel.activateCommon(true);
      ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
      this.getGui().displayElementSettings(containerPortletModel.getSubportlets().get(index));
    }
  }



  /**
   * Set the displayed portlet.
   * 
   * @param model
   *          the displayed portlet model.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void setElement(PortletModel model)
  {
    super.setElement(model);
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
    this.getLabelType().setText(this.getLabelType().getText() + " : " + containerPortletModel.getElementName());
    ElementViewPanel panel = null;
    for (PortletModel subPortlet : containerPortletModel.getSubportlets()) {
      panel = this.getViewPanel(subPortlet.getUniqueID());
      if (panel == null) {
        panel = this.portletViewFactory.createView(subPortlet);
        panel.setParentPanel(this);
        this.subViewPanels.add(panel);
      }
      else {
        panel.setElement(subPortlet);
      }
    }
    this.displaySubportlets();
  }



  /**
   * Update the displayed portlet.
   * 
   * @param updatedModel
   *          the displayed portlet model.
   */
  @Override
  public void updateElement(PortletModel updatedModel)
  {
    super.updateElement(updatedModel);
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
    ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> newPanel = null;
    if (!this.getElement().getUniqueID().equals(updatedModel.getUniqueID())) {
      if (this.getElement().getUniqueID().equals(updatedModel.getParentID())) {
        int index = this.indexOf(updatedModel.getUniqueID());
        if (index == -1) {
          containerPortletModel.getSubportlets().add(updatedModel);
          newPanel = this.portletViewFactory.createView(updatedModel);
          newPanel.setParentPanel(this);
          this.subViewPanels.add(newPanel);
        }
        else {
          containerPortletModel.getSubportlets().remove(index);
          containerPortletModel.getSubportlets().add(index, updatedModel);
          ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> panel = this.subViewPanels.get(index);
          panel.setElement(updatedModel);
        }
      }
      else {
        for (ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> submodel : this.subViewPanels) {
          submodel.updateElement(updatedModel);
        }
      }
    }
    if (newPanel != null) {
      this.deactivateAll();
      newPanel.activateCommon(true);
      this.getGui().displayElementSettings(updatedModel);
    }
    this.displaySubportlets();
  }



  /**
   * Remove the sub-porlet.
   * 
   * @param model
   *          the sub-portlet model.
   */
  public void removeSubPortlet(PortletModel model)
  {
    ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> viewPanel = this.getViewPanel(model.getUniqueID());
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
    containerPortletModel.getSubportlets().remove(model);
    this.subViewPanels.remove(viewPanel);
    this.displaySubportlets();
  }



  /**
   * Move the sub portlet up.
   * 
   * @param model
   *          the sub-portlet model.
   */
  public void moveUpSubPortlet(PortletModel model)
  {
    int index = this.indexOf(model.getUniqueID());
    if (index != 0) {
      ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
      containerPortletModel.getSubportlets().remove(index);
      containerPortletModel.getSubportlets().add(index - 1, model);
      ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> viewPanel = this.getViewPanel(model.getUniqueID());
      this.subViewPanels.remove(index);
      this.subViewPanels.add(index - 1, viewPanel);
    }
    this.displaySubportlets();
  }



  /**
   * Move the sub portlet down.
   * 
   * @param model
   *          the sub-portlet model.
   */
  public void moveDownSubPortlet(PortletModel model)
  {
    int index = this.indexOf(model.getUniqueID());
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
    int nbSubPortlets = containerPortletModel.getNbSubPortlets();
    if (index != nbSubPortlets - 1) {
      containerPortletModel.getSubportlets().remove(index);
      containerPortletModel.getSubportlets().add(index + 1, model);
      ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> viewPanel = this.getViewPanel(model.getUniqueID());
      this.subViewPanels.remove(index);
      this.subViewPanels.add(index + 1, viewPanel);
    }
    this.displaySubportlets();
  }



  /**
   * Get the index of the sub-portlet.
   * 
   * @param updatedID
   *          the unique sub-portlet ID.
   * @return the index of the sub-portlet.
   */
  private int indexOf(UID updatedID)
  {
    int index = -1;
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
    for (PortletModel submodel : containerPortletModel.getSubportlets()) {
      if (submodel.getUniqueID().equals(updatedID)) {
        index = containerPortletModel.getSubportlets().indexOf(submodel);
        break;
      }
    }
    return index;
  }



  /**
   * Display the sub-portlets.
   */
  private void displaySubportlets()
  {
    this.getSpecificPanel().removeAll();
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();

    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridx = 1;
    constraints.gridy = 1;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.fill = GridBagConstraints.BOTH;
    this.getSpecificPanel().setLayout(layout);

    int index = 1;
    for (ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> panel : this.subViewPanels) {
      if (LayoutDirection.HORIZONTAL.equals(containerPortletModel.getDirection())) {
        constraints.gridx = index;
        constraints.gridy = 1;
        if (index == 1) {
          constraints.insets = new Insets(10, 10, 10, 10);
        }
        else {
          constraints.insets = new Insets(10, 0, 10, 10);
        }
      }
      else {
        constraints.gridx = 1;
        constraints.gridy = index;
        if (index == 1) {
          constraints.insets = new Insets(10, 10, 10, 10);
        }
        else {
          constraints.insets = new Insets(0, 10, 10, 10);
        }
      }
      this.getSpecificPanel().add((JPanel) panel, constraints);
      index++;
    }

    this.getSpecificPanel().revalidate();
    this.revalidate();
    this.repaint();

  }



  /**
   * Deactivate the whole panel.
   */
  @Override
  public void deactivateAll()
  {
    this.deactivateSpecific();
    super.deactivateAll();
  }



  /**
   * Handle the common panel activation.
   * 
   * @param isActivated
   *          Whether the panel is activated.
   */
  @Override
  public void activateCommon(boolean isActivated)
  {
    super.activateCommon(isActivated);
    this.activate(isActivated, this.getSpecificPanel());
  }



  /**
   * Deactivate the specific panel.
   */
  @Override
  public void deactivateSpecific()
  {
    super.deactivateSpecific();
    for (ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> panel : this.subViewPanels) {
      panel.deactivateAll();
    }
  }



  /**
   * Get the view factory.
   * 
   * @return the view factory.
   */
  public PortletViewFactory getViewFactory()
  {
    return this.portletViewFactory;
  }



  /**
   * Display the popup.
   * 
   * @param component
   *          The component.
   * @param x
   *          The x position.
   * @param y
   *          The y position.
   */
  @Override
  public void displayPopup(Component component, int x, int y)
  {
    ContainerPortletModel containerPortletModel = (ContainerPortletModel) this.getElement();
    int nbDisplayedSubPortlets = containerPortletModel.getNbSubPortlets();
    if (nbDisplayedSubPortlets >= containerPortletModel.getMaxNbSubPortlets()) {
      this.getMenuAdd().setEnabled(false);
    }
    else {
      this.getMenuAdd().setEnabled(true);
    }
    if (containerPortletModel.isSubElement()) {
      this.getMenuDelete().setEnabled(true);
      this.getMenuDown().setEnabled(true);
      this.getMenuUp().setEnabled(true);
      if (LayoutDirection.HORIZONTAL.equals(containerPortletModel.getParentDirection())) {
        this.getMenuDown().setEnabled(false);
        this.getMenuUp().setEnabled(false);
        this.getMenuRight().setEnabled(true);
        this.getMenuLeft().setEnabled(true);
      }
      else {
        this.getMenuDown().setEnabled(true);
        this.getMenuUp().setEnabled(true);
        this.getMenuRight().setEnabled(false);
        this.getMenuLeft().setEnabled(false);
      }
    }
    else {
      this.getMenuDelete().setEnabled(false);
      this.getMenuDown().setEnabled(false);
      this.getMenuUp().setEnabled(false);
      this.getMenuRight().setEnabled(false);
      this.getMenuLeft().setEnabled(false);
    }
    this.getPopup().show(component, x, y);
  }



  /**
   * Handle action events.
   * 
   * @param e
   *          the action event.
   */
  @Override
  public void actionPerformed(ActionEvent e)
  {
    super.actionPerformed(e);
    Object source = e.getSource();
    if (source.equals(this.getMenuAdd())) {
      this.addSubElement();
    }
  }



  /**
   * Get the view panel from the portlet or one of its sub-portlet.
   * 
   * @param portletUniqueID
   *          The portlet unique ID.
   * @return the view panel.
   */
  @Override
  public ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> getViewPanel(UID portletUniqueID)
  {
    ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> panel = super.getViewPanel(portletUniqueID);
    if (panel == null) {
      for (ElementViewPanel<PortletEditorGUI, PortletDocumentInternalFrame, PortletModel, PortletType> subpanel : this.subViewPanels) {
        panel = subpanel.getViewPanel(portletUniqueID);
        if (panel != null) {
          break;
        }
      }
    }
    return panel;
  }

}
